package com.mccken.eshop.order.manager.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mccken.eshop.common.utils.NumberUtils;
import com.mccken.eshop.order.dao.order.OrderAutoNoMapper;
import com.mccken.eshop.order.enums.OrderNoTypeEnum;
import com.mccken.eshop.order.exception.OrderBizException;
import com.mccken.eshop.order.exception.OrderErrorCodeEnum;
import com.mccken.eshop.order.manager.OrderNoManager;
import com.mccken.eshop.order.model.entity.OrderAutoNo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2022-08-28 16:47
 **/
@Service
@Slf4j
public class OrderNoManagerImpl implements OrderNoManager {
	
	@Autowired
	private OrderAutoNoMapper orderAutoNoMapper;
	
	@Override
	public String genOrderId(Integer orderNoType, String userId) {

		OrderNoTypeEnum orderNoTypeEnum = OrderNoTypeEnum.parse(orderNoType);
		if (orderNoTypeEnum == null) {
			throw new OrderBizException(OrderErrorCodeEnum.ORDER_NO_TYPE_ERROR);
		}

		return orderNoType + this.getOrderIdKey(userId);
	}

	/**
	 * 获取订单id
	 * @param userId
	 */
	private String getOrderIdKey(String userId) {
		return this.getDateTimeKey() + this.getAutoNoKey() + this.getUserIdKey(userId);
	}

	/**
	 * 截取用户ID的后3位 <p>
	 *     如果UserId的长度大于或等于3，则直接返回；否则前面补0
	 * @param userId
	 * @return
	 */
	private String getUserIdKey(String userId) {
		if (StrUtil.isBlank(userId)) {
			return "000";
		}
		
		if (userId.length() >= 3) {
			return userId.substring(userId.length() - 3);
		}
		
		String userIdKey = userId;
		while (userIdKey.length() != 3) {
			userIdKey = "0" + userIdKey;
		}
		
		return userIdKey;
	}

	/**
	 * 生成订单号中间的8位序列号
	 * @return
	 */
	private String getAutoNoKey() {
		OrderAutoNo orderAutoNo = new OrderAutoNo();
		orderAutoNoMapper.insert(orderAutoNo);
		Long id = orderAutoNo.getId();
		return String.valueOf(NumberUtils.genNo(id, 8));
	}

	private String getDateTimeKey() {
		return DateUtil.format(new Date(), "yyMMdd");
		
	}
}
